package action.system;


import helper.EmailHelper;
import helper.MD5Helper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import dao.system.UserDao;
import entity.User;
import entity.UserInfo;
import sun.awt.AppContext;
import util.GeneralAction;
import util.Globals;
import vo.UserVo;

/**
 * @author Chigco.Orc
 *
 */
public class UserAction extends GeneralAction{

	
	private UserVo uVo;
	
	public String action;    //根据action传的值判断动作
	public String txtloginname;
	public String txtPassword;
	public String txtemail;		//邮箱地址（个人编辑页面的新邮箱地址）
	public String code;


	/*
	 * 用户登录
	 */
	public String msg;
	public String ajax_login;
	public String toLogin(){
		if(action.equals("login")){
			List<User> ls = df.getUserDao().checkUserName(txtloginname);
			//System.out.println("查询出来的list长度:"+ls.size()+"\nList信息:"+ls.get(0).getUserId()+"\t密码："+ls.get(0).getPass()+"\t用户输入："+txtloginname+"\t密码："+txtPassword);
			if(ls.size()>0){
				if(MD5Helper.enc(txtPassword).equals(ls.get(0).getPass())){
					if(((User)ls.get(0)).getState()==0){
						System.out.println("登录成功！");
						((User)ls.get(0)).setLastLoginTime(System.currentTimeMillis()); //设置时间
						this.df.getUserDao().update((User)ls.get(0));
						//将部分用户信息传入Vo
						uVo = new UserVo();
						uVo.setId(((User)ls.get(0)).getId());			//用户id
						uVo.setUserId(((User)ls.get(0)).getUserId());	//用户名
						uVo.seteMail(((User)ls.get(0)).geteMail());			//用户邮箱地址
						uVo.setIntegral(((User)ls.get(0)).getIntegral());		//用户积分
						uVo.setProducts(((User)ls.get(0)).getProducts());
//						uVo.setPass(((User)ls.get(0)).getPass());				//用户密码
						if(!((User)ls.get(0)).getUserInfos().isEmpty()){
							uVo.setName(((User)ls.get(0)).getUserInfos().get(0).getName());		//真实姓名
							uVo.setSex(((User)ls.get(0)).getUserInfos().get(0).getSex());				//性别
							uVo.setDate(((User)ls.get(0)).getUserInfos().get(0).getDate());			//生日
							uVo.setTel(((User)ls.get(0)).getUserInfos().get(0).getTel());				//电话
							uVo.setImagesUrl(((User)ls.get(0)).getUserInfos().get(0).getImagesUrl());		//用户头像地址
						}
						//TODO:userinfo传到用户vo。
						uVo.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(((User)ls.get(0)).getLastLoginTime()));		//用户登录时间
						ActionContext.getContext().getSession().put(Globals.loginInfo,uVo);
					}else if(((User)ls.get(0)).getState() == 1){
						msg = "帐号禁止登录！";
					}else{
						msg = "未知错误！请联系管理员";
					}
				}else{
					msg = "密码不正确";
				}
			}else{
				msg = "用户名不正确";
			}
			if ("0".equals(ajax_login)) {
				HttpServletResponse response = ServletActionContext.getResponse();
				try {
					System.out.println("msg:"+msg);
					if(msg == null){
						msg = "0";
						response.getWriter().print("0");
						System.out.println("ajax登录输出msg为："+ 0);
					}else{
						response.getWriter().print(msg);
					}
					System.out.println("ajax登录成功！");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		return "toLogin";
	}
	/*
	 * 用户退出
	 */
	public String toLogout(){
		if(ActionContext.getContext().getSession().get(Globals.loginInfo) != null){
			ActionContext.getContext().getSession().remove(Globals.loginInfo);
		}
		return "toIndex";
	}
	/*
	 * 用户注册
	 */
	public String username;  //get传的值
	public String inputCode;
	//更多资料
	public String more_info;			//1为填写更多资料
//	public String txtTruename;				//真实姓名
//	public String txtBirthday;			//出生日期
	public String gender;				//性别.m男。f女
	public String toReg(){
		if(action.equals("toRegister")){
			System.out.println("action执行toRegister判断通过！!");
			uVo = new UserVo(txtloginname,MD5Helper.enc(txtPassword),txtemail,System.currentTimeMillis());
			System.out.println("准备判断验证码！" + ActionContext.getContext().getSession().get("validateCode") + "\t用户输入的：" + code);
			if(ActionContext.getContext().getSession().get("validateCode").equals(code.toLowerCase())){
				System.out.println("验证码通过！准备调用UserDao的isReg方法！");
				this.df.getUserDao().isReg(uVo);
				//如果选中了填写更多资料
				if("1".equals(more_info)){
					System.out.println("是否填写更多资料："+(more_info.equals("1")?"是":"否")+"真实姓名："+txtTruename+"\t出生日期："+txtBirthday+"\t性别："+gender+"邮编："+txtZip+"\t移动电话:"+txtMobilephone+"\t固定电话:"+txtPhone+"\t其他联系电话："+txtOtherphone);
					userInfo = new UserInfo();
					if (txtTruename != null && !"".equals(txtTruename)) {
						userInfo.setName(txtTruename.toString());
					}
					if(txtBirthday != null && !"".equals(txtBirthday)){
						userInfo.setDate(txtBirthday.toString());
					}
					if(gender != null && !"".equals(gender)){
						userInfo.setSex("m".equals(gender)?1:0);
					}
					if(txtZip != null && !"".equals(txtZip)){
						userInfo.setCode(txtZip);
					}
					userInfo.setUser(df.getUserDao().get("userId", uVo.getUserId()));
					df.getUserInfoDao().save(userInfo);
				}
			}
			System.out.println("用户["+uVo.getUserId()+"]注册成功！");
			return "toLogin";
		}else if(action.equals("checkUserName")){
			//检查用户名
			System.out.println("AJAX调用 checkUserName! "+ username);
			List<User> ls= df.getUserDao().checkUserName(username);
			System.out.println("temp:"+ls.size());
			HttpServletResponse response = ServletActionContext.getResponse();
			try {
				response.getWriter().print(ls.size());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if(action.equals("checkCode")){
			//检查验证码
			System.out.println("AJAX调用 checkCOde! Input: "+ this.inputCode+"\t SysCode:" + ActionContext.getContext().getSession().get("validateCode"));
			int temp;
			if(ActionContext.getContext().getSession().get("validateCode").equals(inputCode.toLowerCase())){
				temp = 0;
			}else{
				temp = 1;
			}
			HttpServletResponse response = ServletActionContext.getResponse();
			try {
				response.getWriter().print(temp);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 编辑个人信息
	 */
	private UserInfo userInfo;
	public String txtTruename;			//真实姓名
	public String txtBirthday;			//出生日期
	public String rdoGender;  //m,f
	public String txtZip;
	public String txtMobilephone; //移动电话
	public String txtPhone;   //固定电话
	public String txtOtherphone;	//其他电话
	public String txtAddress;	//详细地址
	public String txtQQ;	//QQ
	public String txtSKYPE;
	public String txtMSN;	//msn
	public String txtTAOBAO;
	public String txtoldpassword;		//现有密码
//	public String txtemail;		//新邮箱地址
	public String passportName;			//修改密码的用户标识
	public String validatecode;				//修改密码的md5验证码
	public String toOwmMember(){
//		if("editor".equals(action)){
		//通过获取session中的用户的id进行查询
		User u = df.getUserDao().get(Long.valueOf(((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).getId()));
		/*
		 * 编辑个人信息
		 */
		if("modifysave".equals(action)){
			System.out.println("页面请求更新个人信息");
//			u.getUserInfos().add(userInfo);
			List<UserInfo> lsInfos = new ArrayList<UserInfo>();
			userInfo = new UserInfo();
			userInfo.setMsn(txtMSN);
			userInfo.setCode(txtZip);
			userInfo.setOtherPhone(txtOtherphone);
			userInfo.setPhone(txtPhone);
			userInfo.setQq(txtQQ);
			userInfo.setDate(txtBirthday);
			userInfo.setSex(rdoGender.equals("m")?1:0);
			userInfo.setSkype(txtSKYPE);
			userInfo.setTaobao(txtTAOBAO);
			userInfo.setTel(txtMobilephone);
			userInfo.setUser(u);
			//TODO:细节。部分字段未设置
//			u.setUserInfos(lsInfos);
//			lsInfos.add(userInfo);
//			u.setUserInfos(lsInfos);
//			df.getUserDao().save(u);
//			this.df.getUserDao().saveOrUpdate(u);
			df.getUserInfoDao().saveOrUpdate(userInfo);
			System.out.println("用户["+u.getUserId()+"]更新个人资料成功！，进行session的更新！\n出生日期："+userInfo.getDate()+"\t邮编："+userInfo.getCode()+"\t移动电话："+userInfo.getTel());
			//session的更新
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setCode(userInfo.getCode());
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setDate(userInfo.getDate());
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setMsn(userInfo.getMsn());
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setOtherPhone(userInfo.getOtherPhone());
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setPhone(userInfo.getPhone());
			((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).setTel(userInfo.getTel());
		}
		
		/*
		 * 修改密码
		 */
		
		if("passwordsave".equals(action)){
			if(!"".equals(txtPassword.trim()) && txtPassword != null && !"".equals(txtoldpassword) && txtoldpassword != null){
				//判断旧密码是否正确
				if(u.getPass().equals(MD5Helper.enc(txtoldpassword))){
					//产生随机码放到session的value中,key为用户的id;
					HttpSession session = ServletActionContext.getRequest().getSession();
					session.setMaxInactiveInterval(3600 * 72); 			//72小时
					session.setAttribute("changePWD", MD5Helper.enc(txtPassword));
					session.setAttribute(u.getUserId(), MD5Helper.enc(String.valueOf(new Random().nextDouble())));
//					ActionContext.getContext().getSession().put("changePWD", MD5Helper.enc(txtPassword));
//					ActionContext.getContext().getSession().put(u.getUserId(), MD5Helper.enc(String.valueOf(new Random().nextDouble())));
//					System.out.println(ActionContext.getContext().getSession().get(u.getUserId()));
					String contents = "您好！\n欢迎您使用厦门百酷网络商城重设登录密码服务。\n您可以点击或在浏览器中输入以下链接打开重设登录密码的页面。\n\n" +
							"http://www.byku.com.cn/forwardPW.do?passportName="+u.getUserId()+"&validatecode="+ActionContext.getContext().getSession().get(u.getUserId())
							+"\n\n请注意：该链接只能使用一次，并且7日后将自动失效，请您尽快修改。如果需进一步帮助，请联系厦门百酷网络商城的客服人员。" +
									"\n\n此信是厦门百酷网络商城系统发出，系统不接收回信，因此请勿直接回复。  ";
					//			EmailHelper emailHelper = new EmailHelper(host, userName, passWord, mail_head_Name, mail_head_value, mail_to, mail_from, mail_subject, mail_body, personalName);
						EmailHelper sendmail = new EmailHelper("smtp.163.com", "chigco", "damoni", "什么是邮件标题？", "邮件标题带value？", "chigco@qq.com", "chigco@163.com", "百酷网络商城重设登录密码服务确认信 ", contents, "百酷网络商城");
								try {
									sendmail.send();
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								System.out.println("验证通过。数据已经存入session。进行mail发送确认！");
					//TODO:给用户当前的邮箱发送确认修改密码的连接
				}
			}
			if(validatecode != null && !"".equals(validatecode)){
				if(ActionContext.getContext().getSession().get(u.getUserId()).equals(validatecode)){
					u.setPass(ActionContext.getContext().getSession().get("changePWD").toString());
					df.getUserDao().update(u);
					ActionContext.getContext().getSession().remove("changePWD");
					ActionContext.getContext().getSession().remove(u.getUserId());
				}
			}
		}
		
//		if()
		
		
		/*
		 * 修改邮箱地址
		 */
		if("emailsave".equals(action)){
			if(!"".equals(txtemail.trim()) && txtemail != null){
				//TODO:没有判断email是否符合。给旧的email发链接
				u.seteMail(txtemail);
				df.getUserDao().update(u);
			}
		}
			
//			userInfo = df.getUserInfoDao().get(oid)
//			userInfo = new UserInfo();
//			if(userInfo.getName() != null && !userInfo.getName().equals("")){
////				userInfo.setAddress(address);
//				userInfo.setCode(txtZip);
////				userInfo.setDate(date);
//				userInfo.setMsn(txtMSN);
//				userInfo.setOtherPhone(txtOtherphone);
//				userInfo.setPhone(txtPhone);
//				userInfo.setQq(txtQQ);
//				userInfo.setSex(rdoGender.equals("m")?1:0);
//				userInfo.setSkype(txtSKYPE);
//				userInfo.setTaobao(txtTAOBAO);
//				userInfo.setTel(txtMobilephone);
//				userInfo.setUser(df.getUserDao().get(Long.valueOf(((UserVo)ActionContext.getContext().getSession().get(Globals.loginInfo)).getUserId())));
//			}
//			df.getUserInfoDao().saveOrUpdate(userInfo);
			return "toOwmMember";
//		}
//		return "error";
	}
	/**
	 * 找回密码
	 */
}
